<template>
  <div class="regulations-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>法规制度管理</h2>
      <p>管理和维护水库相关的法规制度文档</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon">
          <el-icon>
            <Document />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.total }}</div>
          <div class="stat-label">法规总数</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon active">
          <el-icon>
            <Check />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.active }}</div>
          <div class="stat-label">生效中</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon pending">
          <el-icon>
            <Clock />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.pending }}</div>
          <div class="stat-label">待审核</div>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon expired">
          <el-icon>
            <Warning />
          </el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ stats.expired }}</div>
          <div class="stat-label">已失效</div>
        </div>
      </div>
    </div>

    <!-- 查询条件 -->
    <el-card shadow="hover" style="margin-bottom: 8px">
      <el-form :model="queryForm" inline>
        <el-form-item label="法规名称">
          <el-input v-model="queryForm.name" placeholder="请输入法规名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="法规类型">
          <el-select v-model="queryForm.type" placeholder="请选择法规类型" clearable style="width: 150px">
            <el-option label="国家法律" value="national_law" />
            <el-option label="行政法规" value="administrative_regulation" />
            <el-option label="部门规章" value="departmental_rule" />
            <el-option label="地方法规" value="local_regulation" />
            <el-option label="技术标准" value="technical_standard" />
            <el-option label="管理制度" value="management_system" />
          </el-select>
        </el-form-item>
        <el-form-item label="生效状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="生效中" value="active" />
            <el-option label="待审核" value="pending" />
            <el-option label="已失效" value="expired" />
            <el-option label="已废止" value="abolished" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布时间">
          <el-date-picker v-model="queryForm.dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon>
              <Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="operation-card" shadow="hover" style="margin-bottom: 8px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-button type="primary" plain @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增法规
          </el-button>
          <el-button type="success" plain @click="handleBatchImport">
            <el-icon>
              <Upload />
            </el-icon>
            批量导入
          </el-button>
          <el-button type="warning" plain @click="handleExport">
            <el-icon>
              <Download />
            </el-icon>
            导出数据
          </el-button>
          <el-button type="info" plain @click="handleAnalysis">
            <el-icon>
              <DataAnalysis />
            </el-icon>
            统计分析
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 数据表格 -->
    <el-card shadow="hover">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="法规名称" min-width="200">
          <template #default="{ row }">
            <div class="regulation-name">
              <el-link type="primary" @click="handleView(row)">
                {{ row.name }}
              </el-link>
              <el-tag v-if="row.isImportant" type="danger" size="small" style="margin-left: 8px">
                重要
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="法规类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="number" label="法规编号" width="150" />
        <el-table-column prop="publishDate" label="发布日期" width="120" />
        <el-table-column prop="effectiveDate" label="生效日期" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publisher" label="发布机构" width="150" />
        <el-table-column prop="updateTime" label="更新时间" width="160" />
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" icon="View" @click="viewDetail(row)">查看</el-button>
            <el-button link type="primary" icon="Edit" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="info" icon="Document" plain @click="viewHistory(row)">
              修订历史
            </el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <Pagination :current-page="pagination.currentPage" :page-size="pagination.pageSize" :total="pagination.total"
          @pagination="handlePagination" />
      </div>

    </el-card>



    <!-- 法规表单对话框 -->
    <RegulationFormDialog v-model="formDialogVisible" :regulation="currentRegulation" @success="handleFormSuccess" />

    <!-- 法规详情对话框 -->
    <RegulationDetailDialog v-model="detailDialogVisible" :regulation="currentRegulation" />

    <!-- 修订历史对话框 -->
    <RegulationHistoryDialog v-model="historyDialogVisible" :regulation="currentRegulation" />

    <!-- 修订历史对话框 -->
    <RegulationHistoryDialog v-model="historyDialogVisible" :regulation="currentRegulation" />

    <!-- 统计分析对话框 -->
    <RegulationAnalysisDialog v-model="analysisDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document,
  Check,
  Clock,
  Warning,
  Search,
  Refresh,
  Plus,
  Upload,
  Download,
  DataAnalysis,
  ArrowDown,
  View,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import RegulationFormDialog from './components/RegulationFormDialog.vue'
import RegulationDetailDialog from './components/RegulationDetailDialog.vue'
import RegulationHistoryDialog from './components/RegulationHistoryDialog.vue'
import RegulationAnalysisDialog from './components/RegulationAnalysisDialog.vue'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])

// 统计数据
const stats = reactive({
  total: 156,
  active: 128,
  pending: 15,
  expired: 13
})

// 查询表单
const queryForm = reactive({
  name: '',
  type: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 对话框状态
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const historyDialogVisible = ref(false)
const currentRegulation = ref(null)
const isEdit = ref(false)

// 获取类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap = {
    'national_law': '',
    'administrative_regulation': 'success',
    'departmental_rule': 'info',
    'local_regulation': 'warning',
    'technical_standard': 'danger',
    'management_system': ''
  }
  return typeMap[type] || ''
}

// 获取类型标签文本
const getTypeLabel = (type: string) => {
  const typeMap = {
    'national_law': '国家法律',
    'administrative_regulation': '行政法规',
    'departmental_rule': '部门规章',
    'local_regulation': '地方法规',
    'technical_standard': '技术标准',
    'management_system': '管理制度'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    'active': 'success',
    'pending': 'warning',
    'expired': 'info',
    'abolished': 'danger'
  }
  return statusMap[status] || ''
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statusMap = {
    'active': '生效中',
    'pending': '待审核',
    'expired': '已失效',
    'abolished': '已废止'
  }
  return statusMap[status] || status
}

// 查询
const handleQuery = () => {
  pagination.currentPage = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(queryForm, {
    name: '',
    type: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增
const handleAdd = () => {
  currentRegulation.value = null
  formDialogVisible.value = true
}

// 编辑
const handleEdit = (row: any) => {
  currentRegulation.value = { ...row }
  formDialogVisible.value = true
}

// 查看详情
const viewDetail = (row: any) => {
  currentRegulation.value = row
  detailDialogVisible.value = true
}

// 查看修订历史
const viewHistory = (row: any) => {
  currentRegulation.value = row
  historyDialogVisible.value = true
}

// 批量导入
const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

// 导出
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 统计分析
const handleAnalysis = () => {
  analysisDialogVisible.value = true
}

// 更多操作
const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'download':
      ElMessage.info('下载文档功能开发中...')
      break
    case 'history':
      currentRegulation.value = row
      historyDialogVisible.value = true
      break
    case 'relation':
      ElMessage.info('关联法规功能开发中...')
      break
    case 'delete':
      handleDelete(row)
      break
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除法规"${row.name}"吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    loadData()
  })
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页处理
const handlePagination = (pagination: any) => {
  pagination.currentPage = pagination.page
  pagination.pageSize = pagination.limit
  loadData()
}

// 表单成功回调
const handleFormSuccess = () => {
  loadData()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))

    // 统一生成 10-50 条模拟数据
    const randInt = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1)) + min
    const types = ['national_law', 'administrative_regulation', 'departmental_rule', 'local_regulation', 'technical_standard', 'management_system']
    const publishers = ['全国人大常委会', '国务院', '水利部', '省政府', '国家标准委']
    const count = randInt(10, 50)
    const base: any[] = []
    for (let i = 0; i < count; i++) {
      const year = 2016 + randInt(0, 8)
      const pubMonth = randInt(1, 12)
      const effMonth = Math.min(pubMonth + randInt(0, 3), 12)
      base.push({
        id: i + 1,
        name: `示例法规-${i + 1}`,
        type: types[randInt(0, types.length - 1)],
        number: `NO-${year}-${String(i + 1).padStart(3, '0')}`,
        publishDate: `${year}-${String(pubMonth).padStart(2, '0')}-01`,
        effectiveDate: `${year}-${String(effMonth).padStart(2, '0')}-01`,
        status: ['active', 'pending', 'expired', 'abolished'][randInt(0, 3)],
        publisher: publishers[randInt(0, publishers.length - 1)],
        updateTime: `${year + 7}-12-01 10:30:00`,
        isImportant: !!randInt(0, 1)
      })
    }

    tableData.value = base
    pagination.total = base.length
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.regulations-page {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  background-color: #e3f2fd;
  color: #1976d2;
}

.stat-icon.active {
  background-color: #e8f5e8;
  color: #4caf50;
}

.stat-icon.pending {
  background-color: #fff3e0;
  color: #ff9800;
}

.stat-icon.expired {
  background-color: #ffebee;
  color: #f44336;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.query-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.action-section {
  background: white;
  padding: 16px 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.regulation-name {
  display: flex;
  align-items: center;
}
</style>